<template>
    <div class="ShortAnswer">
        <div class="boxForm">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="题干：" prop="questionsStems">
                    <el-upload
                        class="avatar-uploader"
                        ref="avatar"
                        :action="upImg"
                        name="file"
                        :headers="header"
                        :show-file-list="false"
                        :on-success="uploadSuccess"
                    >
                    </el-upload>
                    <quill-editor 
                        ref="myQuillEditor" 
                        :options="editorOption"
                        v-model="ruleForm.questionsStems"
                    >
                    </quill-editor>
                </el-form-item>
                <el-form-item label="标答：" prop="answerNofixed">
                    <el-input
                        v-model="ruleForm.answerNofixed"
                        placeholder="请输入标准答案"
                    ></el-input>
                </el-form-item>
                <el-form-item label="解析：" prop="parse">
                    <el-input v-model="ruleForm.parse"></el-input>
                </el-form-item>
                <el-form-item label="分数" prop="grades">
                    <el-input-number v-model="ruleForm.grades" @change="handleChange" :min="0" :max="10" label="描述文字"></el-input-number>
                </el-form-item>
                <el-form-item label="难度" prop="difficulty">
                    <el-rate class="aa" v-model="ruleForm.difficulty"></el-rate>
                </el-form-item>
                <el-form-item label="知识点" prop="knowledgePoint">
                    <el-input v-model="ruleForm.knowledgePoint"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
                    <el-button @click="resetForm('ruleForm')">重置</el-button>
                    <el-button @click="preview">预览</el-button>
                    <el-button @click="goBack">返回</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import {
    addQuertionBankApi,
    getGradeListApi,
    getCourseListApi,
    EditQuertionBankApi,
    getQuertionBankListApi 

} from "@/api/onlinehomework/questionbank.js"
import {HOST} from "@/global.js"
//  配置富文本选项
const toolbarOptions = [
  ["image"], // 链接、图片、视频-----['link', 'image', 'video']
]
import { getToken } from "@/utils/auth";

export default {
    name:'ShortAnswer',
    props:['selectIndex','gradeId','subjectId','row'],
    data() {
        return {
            ruleForm: {
                questionsStems: '', // 题干
                answerNofixed: '', // 标答
                parse: '', //  解析
                grades: '', // 分数
                difficulty: 0, // 难度
                knowledgePoint: '', // 知识点
                // options:[],
            },
            rules: {
                gradeName: [
                    { required: true, message: '请选择年级', trigger: 'blur' },
                ],
                subject: [
                    { required: true, message: '请选择学科', trigger: 'change' }
                ],
                questionsStems: [
                    {  required: true, message: '请输入题干', trigger: 'change' }
                ],
                answerNofixed: [
                    { required: true, message: '标准答案', trigger: 'change' }
                ],
                parse: [
                    {  message: '解析', trigger: 'change' }
                ],
                grades: [
                    { required: true, message: '分数', trigger: 'change' }
                ],
                difficulty: [
                    { required: true, message: '难度', trigger: 'change' }
                ],
                knowledgePoint: [
                    { message: '知识点', trigger: 'change' }
                ],
            },
            dialogFormVisible: false, // 预览开关
            inde:'',
            upImg:`${HOST}/file/upload`,
            header: {
                Authorization: `Bearer ${getToken()}`,
            },
            // 富文本
            editorOption: {
                placeholder: "请在这里输入",
                theme: "snow", //主题 snow/bubble
                modules: {
                history: {
                    delay: 1000,
                    maxStack: 50,
                    userOnly: false,
                },
                toolbar: {
                        container: toolbarOptions,
                        handlers: {
                            image: function (value) {   
                                if (value) {
                                    console.log(value);
                                    // 调用element的图片上传组件
                                    console.log(this);
                                    console.log(document.querySelector(".avatar-uploader"));
                                    // console.log(document.getElementById("avatar"));
                                    document.querySelector(".avatar-uploader input").click();
                                } else {
                                    this.quill.format("image", false);
                                }
                            },
                            image1: function (value) {   
                                if (value) {
                                    console.log(value);
                                    // 调用element的图片上传组件
                                    console.log(this);
                                    console.log(document.querySelector(".avatar-uploader"));
                                    // console.log(document.getElementById("avatar"));
                                    document.querySelector(".avatar-uploader1 input").click();
                                } else {
                                    this.quill.format("image", false);
                                }
                            },
                        },
                    },
                },
            },

        }
    },
    computed:{
        gradeName() {
            return ''
            // return  this.gradeOptions.filter(item=>{
            //     return item.typeId === this.gradeId
            // })
        },
        subjectName() {
            return ''
            // return this.subjectOptions.filter(item=>{
            //     return item.courseTypeId === this.subjectId
            // })
        },
        // routeRow() {
        //     if(this.$route.params.row) {
        //         return this.ruleForm = this.$route.params.row
        //     }else {
        //         return ''
        //     }
        // }
    },
    watch: {
        '$route':function(){
        // console.log('watch里面',this.$route.name);
        // if(this.$route.name === 'home'){
        //   this.isHomeRouter = true;
        // }else{
        //   this.isHomeRouter = false;
        // }
        console.log(this.$route,'监听路由变化')
      }
  },
    mounted(){
        console.log(this.row,'----------tabIndex');

        // console.log(this.ruleForm,'pppp');
        // console.log(this.$route.params.row,'pppp');
        // console.log(this.gradeName);
        this.inde = this.$route.params.tabIndex
        if(this.$route.params.isEdit == '1') {
           console.log(123123123);
            getQuertionBankListApi({pageSize:"10",pageNum:this.$route.params.currentPage}).then(res=>{
                console.log(res,'-----');
                let filterItem = res.rows.filter(item=>{
                    console.log(item);
                    return item.questionsId == this.$route.params.row
                })
                console.log(filterItem[0]);
                this.ruleForm = filterItem[0]
                this.ruleForm.difficulty = Number(this.ruleForm.difficulty)
                console.log(this.ruleForm,'pppp');
            })

        //     this.ruleForm.options = JSON.parse(this.$route.params.row.options)
        }
        // getGradeListApi().then(res=>{
        //     console.log(res);
        //     this.gradeOptions = res.rows
        // })
        // console.log(this.$route.params,'-------------rowsssss');
        getGradeListApi({parentId:55}).then(res=>{
            console.log(res);
            this.gradeOptions = res.rows
            // this.gradeOptions.forEach(item=>{
            //     item.
            // })
        })
       
        getCourseListApi().then(res=>{
            this.subjectOptions = res.rows
            console.log(this.subjectOptions);
            console.log(this.$route.params);
        })
    
    },
    methods:{
        // 返回
        goBack() {
            this.$router.push({
                path:"/onlinehomework/questionbank/questionBankList"
            })
        },
        // 上传图片成功返回事件
        uploadSuccess(res) {
            // 获取富文本组件实例
            let quill = this.$refs.myQuillEditor.quill;
            console.log(quill,'-------选项上传');
            // 如果上传成功
            if (res) {
                // 获取光标所在位置
                let length = quill.getSelection().index;
                // 插入图片，res为服务器返回的图片链接地址
                quill.insertEmbed(length, "image", res.data.url);
                // 调整光标到最后
                quill.setSelection(length + 1);
            } else {
                // 提示信息，需引入Message
                this.$message.error("图片插入失败！");
            }
            this.quillUpdateImg = false;
        },
        handleChange() {},
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if(this.$route.params.isEdit === '0') {
                    if (valid) {
                        let obj = {
                            questionsStems:this.ruleForm.questionsStems,
                            questionsType:Number(this.selectIndex),
                            answerNofixed:this.ruleForm.answerNofixed,
                            grades:this.ruleForm.grades,
                            difficulty:this.ruleForm.difficulty,
                            knowledgePoint:this.ruleForm.knowledgePoint,
                            parse:this.ruleForm.parse,
                            grade:this.gradeId,
                            subject:this.subjectId

                        }
                        addQuertionBankApi(obj).then(res=>{
                            console.log(res,'------------>添加');
                            if(res.code === 200) {
                                this.$message({
                                    type: 'success',
                                    message: '添加成功',
                                });
                                this.$router.push({
                                    path:"/onlinehomework/questionbank/questionBankList"
                                })
                            }else {
                                this.$message({
                                    type: 'error',
                                    message: '添加失败',
                                });
                            }
                        })
                    } 
                }else {
                    console.log(this.ruleForm);
                    let obj = {
                        questionsStems:this.ruleForm.questionsStems,
                        questionsType:Number(this.selectIndex),
                        answerNofixed:this.ruleForm.answerNofixed,
                        grades:this.ruleForm.grades,
                        difficulty:this.ruleForm.difficulty,
                        knowledgePoint:this.ruleForm.knowledgePoint,
                        parse:this.ruleForm.parse,
                        grade:this.gradeId,
                        subject:this.subjectId,
                        questionsId:this.ruleForm.questionsId

                    }
                    EditQuertionBankApi(obj).then(res=>{
                        console.log(res,'------------>');
                        if(res.code === 200) {
                            this.$message({
                                type: 'success',
                                message: '修改成功',
                            });
                            this.$router.push({
                                path:"/onlinehomework/questionbank/questionBankList"
                            })
                        }else {
                            this.$message({
                                type: 'error',
                                message: '修改失败',
                            });
                        }
                    })
                }
            });
        },
        // 预览
        preview() {
            this.dialogFormVisible = true
        },
        // 弹框取消确定事件
        cancel() {
            this.dialogFormVisible = false
        },
        sureBtn() {
            this.dialogFormVisible = false
        },
    }

}
</script>

<style lang='scss' scoped>
.ShortAnswer{
    width: 100%;
    height: 100%;
    min-width: 100vh;
    // padding: 0 20px;
    .boxForm{
        width: 100%;
        background-color: #fff;
        padding: 10px 20px 10px 0;
        // border-radius: 10px;
        .boxOption{
            padding: 30px 0;
            .opitonsA,
            .opitonsB,
            .opitonsC,
            .opitonsD{
                display: flex;
                justify-content: space-around;
                margin-top: 10px;
                .option{
                    width: 50px;
                    text-align: center;
                }
                .editor{
                    flex: 1;
                }
                .remove{
                    width: 50px;
                    text-align: center;
                }
            }
            .optionA p{
                width: 50px;
            }
        }
        .el-rate{
            line-height: 2.5;
        }
    }
    ::v-deep .el-dialog{
        width: 600px;
        height: 550px;
        border-radius: 10px 10px 0 0;
        .el-dialog__header {
            border-radius: 10px 10px 0 0;
            text-align: center;
            background-color: rgb(72, 149, 219);
            .el-dialog__title {
                color: #fff;
            }
            .el-dialog__headerbtn .el-dialog__close {
                color: #fff;
            }
        }
        .dialog-footer {
            text-align: center;
            button {
                width: 100px;
                height: 35px;
                border-radius: 16px;
                line-height: 0;
            }
            .cancel {
                border: none;
                color: #848383;
                background-color: #f0f0f0;
            }
            .determine {
                border: none;
                background-color: #4995dc;
            }
        }
        .infoDialog{
            // width: 700px;
            // height: 500px;
            .grade{
                width: 100%;
                height: 40px;
                .gradeBox{
                    display: flex;
                    p:first-child{
                        width: 80px;
                    }
                }
                .subject{
                    display: flex;
                    p:first-child{
                        width: 80px;
                    }
                }
            }
            .testQuestions,
            .stem,
            .bidAnswers,
            .analysis,
            .fraction,
            .difficulty,
            .Knowledge
            {
                display: flex;
                width: 100%;
                height: 40px;
                align-items: center;
                p:first-child{
                    width: 80px;
                    // text-align: right;
                }
            }
        }
    }
}
</style>